<template>
  <Input-Global-Data :value="connectStore">
    <div class="indexinput">
      <div class="indexinput-head">
        <div v-show="!isHeadBtnBack" class="indexinput-head-r">
          <el-button v-if="isCZUser" size="small" type="primary" @click="indexUpdata">指标添加</el-button>
          <el-button size="small" class="btn-blue" @click="exportIndexInput">导出</el-button>
        </div>

        <div v-show="isHeadBtnBack" class="indexinput-head-l">
          <el-button class="btn-blue" size="small" @click="isHeadBtnBack = false">返回</el-button>
        </div>
      </div>

      <div class="indexinput-container">
        <div v-if="!isHeadBtnBack">
          <My-Form @filterFormSearch="filterFormSearch" />
          <el-pagination
            class="indexinput-page"
            :current-page="pageIndex"
            :page-sizes="[100, 200, 300, 400]"
            :page-size="pageSize"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"
          />
          <!-- // ! 表格 -->
          <vxe-grid
            ref="xGrid"
            :span-method="spanMethod"
            v-bind="gridOptions"
            round
            :header-cell-style="headerCellStyle"
            :cell-style="cellStyle"
          >
            <template #show_money="{ row }">
              <div>{{ AmountSlite(row.money) }}</div>
            </template>
          </vxe-grid>
        </div>

        <div v-else>
          <!-- //! 指标新增 -->
          <Index-Add @successBack="isHeadBtnBack = false" />
        </div>
      </div>
      <EditDialog @editRowInfo="editRowInfo" />
    </div>
  </Input-Global-Data>
</template>

<script type="text/ecmascript-6">
import MyForm from '@/views/indexInput/components/Form';
import IndexAdd from '@/views/indexInput/components/IndexAdd';
import EditDialog from '@/views/indexInput/components/EditDialog';
import { downloadFile } from '@/utils/commonMethods';
import { AmountSlite } from '@/utils/utils';
import { getFilePage, fileView, downFile } from '@/api/file';
import _ from 'lodash';
import {
  getBudgetList,
  getBudgetByCode,
  exportBudget,
  delBudget
} from '@/api/indexInput';

const fileUpGuidAddition = 'indexinput-';
const InputGlobalData = {
  name: 'InputGlobalData',
  props: {
    value: {
      type: [Array, String, Object, Function, Number, Boolean],
      default: () => ({})
    }
  },

  provide() {
    return {
      connectStore: this.$props
    };
  },
  render() {
    const { $slots } = this;
    return $slots && $slots.default;
  }
};

const FileAction = {
  name: 'FileAction',
  props: ['row', 'type'],
  computed: {
    files() {
      let files = [];
      if (typeof this.row === 'object') {
        files = this.row.annex.split(',');
      }
      return files;
    }
  },
  methods: {
    async fileAction(fileName) {
      const { row, type } = this;
      const guid = fileUpGuidAddition + row.guid;
      const loadingConfig = {
        lock: true,
        text: '正在下载',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      };
      const { data: fileList } = await this.getFilePage(guid);
      const fileNow = fileList.find(file => file.originName === fileName);

      // 下载进度
      const downProgress = progress => {
      };
      const fileDown1 = row => {
        const loading = this.$loading(loadingConfig);
        downFile({ fileName, filePath: fileNow.path }, downProgress).then(blob => {
          downloadFile(blob.data, fileName, blob.data.type);
          loading.close();
        }).catch(() => {
          loading.close();
          this.$message.warning('下载文件失败');
        });
      };

      const fileView1 = row => {
        fileView(fileNow.id);
      };

      const eventMap = {
        down: fileDown1,
        view: fileView1
      };
      if (fileNow) {
        eventMap[type](row);
      } else {
        this.$message.warning('找不到该文件');
      }
    },

    getFilePage(guid) {
      return getFilePage({
        pageIndex: 0,
        pageSize: 500,
        guid
      });
    }
  },
  render() {
    return (
      <div class='indexInput-file-action'>
        {this.files.map((file) => {
          return (<div>
            <label>{file}</label>
            <el-button onclick={() => this.fileAction(file)} type='text'>{this.type === 'view' ? '预览' : '下载'}</el-button>
          </div>);
        })}
      </div>
    );
  }
};

export default {
  components: {
    InputGlobalData,
    MyForm,
    IndexAdd,
    EditDialog,
    // eslint-disable-next-line vue/no-unused-components
    FileAction
  },
  data() {
    const minColunmsWidth = '157px';
    return {
      isCZUser: false, // (是否财政用户， 显示一些操作按钮)
      total: 0,
      pageIndex: 1,
      pageSize: 100,
      searchData: {},
      tableHeight: '',
      chooseYear: '', // 系统选中的年
      userId: '',
      isHeadBtnBack: false, // 显示返回按钮？
      connectStore: {
        isEditDialogShow: false,
        rowNow: {},
        fileUpGuidAddition // 多文件上传时guid前面额外添加的东西
      },

      gridOptions: {
        border: true,
        resizable: true,
        height: this.tableHeight,
        checkboxConfig: {
          reserve: true
        },
        treeConfig: {
          lazy: true,
          accordion: true,
          trigger: 'row',
          children: 'children',
          hasChild: 'hasChild', // 设置是否有子节点标识
          loadMethod: ({ row }) => { // 点击展开树调用
            return new Promise(resolve => {
              this.getBudgetByCode(row.code).then(res => {
                res.forEach((item) => {
                  item.parent = row;
                });
                resolve(res);
              });
            });
          }
        },
        proxyConfig: {
          ajax: {
            query: () => { // 载入时调用
              return new Promise(resolve => {
                this.getBudgetList().then(res => {
                  resolve(res.data);
                });
              });
            }
          }
        },
        columns: [
          { type: 'checkbox', width: 50 },
          { field: 'operating', title: '操作', minWidth: '157px', treeNode: true, slots: {
            default: ({ row }) => {
              if (row.isParent) {
                return [
                  <div class='indexinput-table-parent' ondblclick={() => this.expandRecords(row)} >
                    <span>单号</span>
                    <span>{row.code}</span>
                    <span class='indexinput-table-parent-je'>金额: {AmountSlite(row.money)}</span>
                  </div>
                ];
              } else {
                if (this.isCZUser) {
                  return [
                    <div class='indexinput-table-cell-operating'>
                      <el-button onClick={() => this.delectRow(row)} type='text'><span style='color:#FF4D4F;'>删除</span></el-button>
                      <el-button onClick={() => this.editRow(row)} type='text'>修改</el-button>
                    </div>
                  ];
                } else {
                  return [
                    <div style='indexinput-table-cell-operating-null'></div>
                  ];
                }
              }
            }
          }},
          { field: 'rn', minWidth: '120px', title: '编号' },
          { field: 'enterpriseName', minWidth: '200px', title: '乡镇' },
          { field: 'divisionName', minWidth: minColunmsWidth, title: '归口' },
          { field: 'programName', minWidth: minColunmsWidth, title: '项目名称' },
          { field: 'resourceName', minWidth: minColunmsWidth, title: '资金来源' },
          { field: 'budgetcategoryName', minWidth: minColunmsWidth, title: '指标类型' },
          {
            title: '功能科目',
            children: [
              { field: 'functionCode', minWidth: minColunmsWidth, title: '编码' },
              { field: 'functionName', minWidth: minColunmsWidth, title: '名称' }
            ]
          },
          { field: 'money', minWidth: minColunmsWidth, title: '金额', slots: { default: 'show_money' }},
          {
            title: '文件依据',
            children: [
              { field: 'fileNo', minWidth: minColunmsWidth, title: '文号' },
              { field: 'postFileDate', minWidth: minColunmsWidth, title: '发文日期' }
            ]
          },
          {
            title: '原文件依据',
            children: [
              { field: 'originalFileNo', minWidth: minColunmsWidth, title: '原文号' },
              { field: 'originalFileDate', minWidth: minColunmsWidth, title: '原发文日期' }
            ]
          },

          { field: 'accountDate', minWidth: minColunmsWidth, title: '入账日期' },
          { field: 'remark', minWidth: minColunmsWidth, title: '备注' },
          { field: 'type', title: '附件', minWidth: minColunmsWidth, fixed: 'right', slots: {
            default: ({ row }) => {
              if (row.annex === '') {
                return [
                  <div class='indexinput-table-cell-operating'>
                    <el-button type='text'>暂无附件</el-button>
                  </div>
                ];
              } else {
                return [
                  <div class='indexinput-table-cell-operating'>
                    <el-button onClick={() => this.fileRelated(row, 'view')} type='text'><span >预览</span></el-button>
                    <el-button onClick={() => this.fileRelated(row, 'down')} type='text'>下载</el-button>
                  </div>
                ];
              }
            }
          }}
        ]
      }

    };
  },
  mounted() {
    this.tableHeight =
      window.innerHeight - this.$refs.xGrid.$el.offsetTop - 598;
    this.tableHeight = 80;
  },

  created() {
    this.chooseYear = localStorage.getItem('chooseYear');
    this.userId = localStorage.getItem('xcUserId');
    const xcRoleName = localStorage.getItem('xcRoleName');
    if (xcRoleName && xcRoleName.includes('财政')) {
      this.isCZUser = true;
    }
  },

  methods: {
    AmountSlite,

    expandRecords(row) {
      this.$refs.xGrid.reloadTreeChilds([row]);
    },

    // 分页相关
    handlePageSizeChange(v) {
      this.pageIndex = 1;
      this.pageSize = v;
      this.reloadXGrid();
    },

    handleCurrentChange(v) {
      this.pageIndex = v;
      this.reloadXGrid();
    },

    // 查询
    filterFormSearch(filterList) {
      const copyFilterList = _.cloneDeep(filterList);
      const eventMap = {
        enterpriseCode: (value, item) => {
          item.enterpriseCode = value.split(' ')[0];
        },
        functionCode: (value, item) => {
          item.functionCode = value.split(' ')[0];
        },
        money: (value, item) => {
          if (value[0] !== '') {
            item.startMoney = value[0];
            item.endMoney = value[1];
          }
        },
        originalFileDate: (value, item) => {
          if (value[0] !== '') {
            item.startPostFileDate = value[0];
            item.endPostFileDate = value[1];
          }
        },
        accountDate: (value, item) => {
          if (value[0] !== '') {
            item.startAccountDate = value[0];
            item.endAccountDate = value[1];
          }
        },
        postFileDate: (value, item) => {
          if (value[0] !== '') {
            item.startPostFileDate = value[0];
            item.endPostFileDate = value[1];
          }
        }
      };
      const collectData = {};
      copyFilterList.map(item => {
        if (item.value) {
          if (item.requestKey in eventMap) {
            eventMap[item.requestKey](item.value, collectData);
          } else {
            collectData[item.requestKey] = item.value;
          }
        }
      });

      collectData.year = localStorage.getItem('chooseYear');
      // collectData.userId = localStorage.getItem('xcUserId');
      this.searchData = collectData;
      this.reloadXGrid();
    },

    // 表格重载
    reloadXGrid() {
      this.$refs.xGrid.commitProxy('reload');
    },

    // 修改行
    editRowInfo({ edit, row }) {
      const f = this.$refs.xGrid.getTreeExpandRecords()[0];
      for (const key in edit) {
        const originValue = row[key];
        row[key] = edit[key];
        if (key === 'money') {
          if (originValue !== edit[key]) {
            this.refreshColunms();
            const newMoney = f.children.reduce((prev, curr) => {
              prev += (curr.money * 1);
              return prev;
            }, 0);
            f.money = newMoney;
          }
        }
      }
      this.refreshColunms();
    },

    // 指标跟新
    indexUpdata() {
      this.isHeadBtnBack = true;
    },

    // 获取指标列表(父节点)
    getBudgetList() {
      const requestData = Object.keys(this.searchData).length ? this.searchData : { year: localStorage.getItem('chooseYear') };
      requestData.pageIndex = this.pageIndex - 1;
      requestData.pageSize = this.pageSize;
      if (!('enterpriseCode' in requestData)) {
        const enterpriseList = JSON.parse(localStorage.getItem('enterprise_jc'));
        const enterpriseCode = enterpriseList.reduce((prev, curr) => {
          prev.push(curr.ISBN_CODE);
          return prev;
        }, []).join(',');
        requestData.enterpriseCode = enterpriseCode;
      }

      return getBudgetList(requestData).then(res => {
        this.searchData = {};
        if (res.success) {
          res.data.forEach((item, id) => {
            item.hasChild = true;
            item.isParent = true;
            item.id = id + item.code;
          });
          this.tableData = res.data;
          this.total = res.total;
          return Promise.resolve(res);
        }
        this.$message.warning(res.message);
        return Promise.resolve([]);
      });
    },

    // 获取指标列表(zi节点)
    getBudgetByCode(code) {
      const requestData = {
        'year': this.chooseYear,
        // 'userId': this.userId,
        'code': code
      };
      return getBudgetByCode(requestData).then(res => {
        return new Promise((resolve, reject) => {
          if (res.success) {
            res.data.forEach(item => {
              item.isDownLoading = false;
            });
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },

    // 获取复选框选中
    getChecked() {
      const checkedXGrid = this.$refs.xGrid.getCheckboxRecords();
      const checkObj = {};
      checkedXGrid.map(item => {
        checkObj[item.code] = 1;
      });
      return Object.keys(checkObj);
    },

    // 导出
    exportIndexInput() {
      const checked = this.getChecked();
      if (checked.length) {
        const requestData = {
          'year': localStorage.getItem('chooseYear'),
          // 'userId': localStorage.getItem('xcUserId'),
          code: checked.join(',')
        };
        exportBudget(requestData).then(res => {
          downloadFile(res, `指标录入.xls`, '.xls');
        });
      } else {
        this.$message.warning('请先勾选某条记录');
      }
    },

    delectRow(row) {
      this.$confirm('确认删除该条指标？', undefined, {
        type: 'warning',
        title: '指标删除'
      }).then(() => {
        delBudget({
          'guidList': [row.guid + '']
        }).then(res => {
          if (res.success) {
            const xGrid = this.$refs.xGrid;
            let [x, y] = [-1, -1];

            xGrid.tableData.forEach((p, pindex) => {
              if (p.children && p.children.length) {
                p.children.forEach((c, cindex) => {
                  if (c._XID === row._XID) {
                    [x, y] = [pindex, cindex];
                  }
                });
              }
            });
            xGrid.tableData[x].children.splice(y, 1);
            if (xGrid.tableData[x].children.length === 0) {
              xGrid.tableData.splice(x, 1);
            }
            this.refreshColunms();
            this.$message.success(res.message);
          } else {
            this.$message.warning(res.message);
          }
        });
      });
    },

    editRow(row) {
      this.connectStore.rowNow = row;
      this.connectStore.isEditDialogShow = true;

      this.refreshColunms();
    },

    // 更新表视图 刷新列配置
    refreshColunms() {
      this.$refs.xGrid.refreshColumn();
    },

    // 获取勾选数据
    getCheckboxRecords() {
      return this.$refs.xGrid.getCheckboxRecords();
    },

    spanMethod(scoped) {
      const { row, _columnIndex } = scoped;
      if (row.isParent) {
        const colunmIndexMap = {
          0: { rowspan: 1, colspan: 1 },
          1: { rowspan: 1, colspan: this.gridOptions.columns.length + 2 }
        };
        if (_columnIndex in colunmIndexMap) {
          return colunmIndexMap[_columnIndex];
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }
      return { rowspan: 1, colspan: 1 };
    },

    headerCellStyle({ column }) {
      const style = {
        'background-color': '#1890FF',
        'height': '44px',
        'color': '#fff'
      };
      if (column.children && column.children.length) {
        style['text-align'] = 'center';
      }
      return style;
    },

    // 附件相关  附件那一列点击
    fileRelated(row, type) {
      const h = this.$createElement;
      const title = type === 'down' ? '下载文件' : '预览文件';
      this.$msgbox({
        title,
        showConfirmButton: false,
        message: h('div', null, [
          h('File-Action', {
            props: {
              row,
              type
            },
            on: {
              'fileLoading': flag => {
                row.isDownLoading = flag;
                this.refreshColunms();
              }
            }
          }, '')
        ])
      });
    },

    cellStyle(scoped) {
      const { row, _columnIndex } = scoped;
      const style = {
        'height': '54px'
      };

      if (!row.isParent) {
        if (_columnIndex > 1) {
          style['background-color'] = '#F2F2F2';
        } else if (_columnIndex === 1) {
          if (this.isCZUser) {
            style['background-color'] = '#E6F7FF';
          } else {
            style['background-color'] = '#F2F2F2';
          }
        }
      }
      return style;
    }

  }
};
</script>

<style lang="scss" scoped>
.indexinput-container /deep/ .vxe-table.border--full .vxe-body--column, .vxe-table.border--full .vxe-footer--column, .vxe-table.border--full .vxe-header--column{
  height: 10px !important;
}

.indexinput {
  width: 100%;
  height: 100%;
  padding: 10px 15px;

  .indexinput-head {
    background-color: #fff;
    padding: 12px 20px;

    .indexinput-head-r {
      text-align: right;
    }
  }

  .indexinput-container {
    background-color: #fff;
    margin: 8px 0;
    padding: 10px 0px;
    min-height: calc(100% - 56px - 10px);
  }

  .indexinput-page {
    margin-bottom: 10px;
  }

  /deep/ .btn-blue {
    color: #1890FF;
    border-color: #1890FF;
  }
}

/deep/ .tree-node-parent-content {
  display: flex;
  justify-content: space-between;
  width: 300px;
}

/deep/ .indexinput-table-parent {
  color: #000000;
  font-weight: 600;
  .indexinput-table-parent-je {
    margin-left: 60px;
  }
}

/deep/ .indexinput-table-cell-operating {
  width: 100%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #E6F7FF;
}

/deep/ .indexInput-file-action {
  > div {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px;
    transition: linear .2s;
    &:hover {
      background-color: #F4F4F5;
    }
  }
}

/deep/ .el-collapse-item__content {
  .el-date-editor {
  padding: 0 3px;
  input {
      font-size: 12px;
      width: 45%;
    }
    .el-range-separator {
      text-align: center;
      display: flex;
      justify-content: center;
    }
  .el-range__icon {
    display: none;
  }
  .el-range__close-icon {
    width: 10px;
  }
}
}

</style>
